﻿namespace S7.Net
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Text;

    public static class Logger
    {
        public static string ComplexDataFlag = "{E7192C4A-328B-446c-AA07-0DC3912FFAE9}";
        private static DefaultTraceListener consoleTrace = new DefaultTraceListener();
        private static string LastTraceFile = string.Empty;
        private static TextWriterTraceListener listner = null;
        private static object lockObject = new object();
        private static string ProcessID = string.Empty;
        private static string ProcessName = string.Empty;
        private static string Seperator = "\r\n\r\n";
        private static string TRACE_FILE = string.Empty;
        private static string TRACE_FILE_PATH = string.Empty;
        private static int TRACE_FILE_SIZE = 20;
        private static int TraceLevel = 0;
        private static TextWriterTraceListener TraceLogListner = null;
        private static string TracePath = string.Empty;
        private static int TraceSize = 20;
        private static bool WriteFlag = true;

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileInt(string lpAppName, string lpKeyName, int nDefault, string lpFileName);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);
        public static void Init()
        {
            try
            {
                string str2;
                string str4;
                Process currentProcess = Process.GetCurrentProcess();
                ProcessID = currentProcess.Id.ToString();
                ProcessName = currentProcess.ProcessName;
                if (!File.Exists(Path.Combine(Path.GetDirectoryName(currentProcess.MainModule.FileName), "Log.ini")))
                {
                    str2 = Path.Combine(Path.GetDirectoryName(currentProcess.MainModule.FileName), "LogFile");
                    TracePath = str2;
                    if (!Directory.Exists(str2))
                    {
                        Directory.CreateDirectory(TracePath);
                    }
                    str4 = Path.Combine(Path.GetDirectoryName(currentProcess.MainModule.FileName), "Log.ini");
                    if (!File.Exists(str4))
                    {
                        new FileStream(str4, FileMode.Create).Close();
                        WriteString(str4, "Trace", "Path", str2);
                        WriteString(str4, "Trace", "Level", "4");
                    }
                    TraceLevel = 4;
                    TraceSize = 20;
                }
                else
                {
                    str2 = ReadString(Path.Combine(Path.GetDirectoryName(currentProcess.MainModule.FileName), "Log.ini"), "Trace", "Path", "");
                    TracePath = str2;
                    if (!Directory.Exists(str2))
                    {
                        Directory.CreateDirectory(TracePath);
                        str4 = Path.Combine(Path.GetDirectoryName(currentProcess.MainModule.FileName), "Log.ini");
                        if (!File.Exists(str4))
                        {
                            new FileStream(str4, FileMode.Create).Close();
                            WriteString(str4, "Trace", "Path", str2);
                            WriteString(str4, "Trace", "Level", "2");
                        }
                    }
                    TraceLevel = int.Parse(ReadString(Path.Combine(Path.GetDirectoryName(currentProcess.MainModule.FileName), "Log.ini"), "Trace", "Level", "2"));
                    TraceSize = ReadInt(Path.Combine(Path.GetDirectoryName(currentProcess.MainModule.FileName), "Log.ini"), "Trace", "Size", 20);
                }
            }
            catch
            {
            }
        }

        private static int ReadInt(string file, string section, string key, int def)
        {
            return GetPrivateProfileInt(section, key, def, file);
        }

        private static string ReadString(string file, string section, string key, string def)
        {
            StringBuilder lpReturnedString = new StringBuilder(0x400);
            GetPrivateProfileString(section, key, def, lpReturnedString, 0x400, file);
            return lpReturnedString.ToString();
        }

        public static void SetWriteFlag(bool flag)
        {
            WriteFlag = flag;
        }

        public static void TextTrace(string traceName, string traceMessage)
        {
            StringBuilder builder = null;
            TRACE_FILE_PATH = ReadString(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "Log.ini"), "Trace", "Path", "");
            TRACE_FILE_SIZE = ReadInt(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "Log.ini"), "Trace", "Size", 20);
            if (!Directory.Exists(TRACE_FILE_PATH))
            {
                TRACE_FILE_PATH = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
                string path = Path.Combine(TRACE_FILE_PATH, "Log.ini");
                if (!File.Exists(path))
                {
                    new FileStream(path, FileMode.Create).Close();
                }
                WriteString(path, "Trace", "Path", TRACE_FILE_PATH);
            }
            TRACE_FILE = Path.Combine(TRACE_FILE_PATH, DateTime.Now.ToString("yyyy-MM-dd") + ".log");
            bool flag = false;
            int num = 0;
            while (!flag)
            {
                if (File.Exists(TRACE_FILE))
                {
                    FileInfo info = new FileInfo(TRACE_FILE);
                    float num2 = ((float) info.Length) / 1000000f;
                    if (num2 > TRACE_FILE_SIZE)
                    {
                        TRACE_FILE = Path.Combine(TRACE_FILE_PATH, DateTime.Now.ToString("yyyy-MM-dd_") + num.ToString() + ".log");
                        num++;
                    }
                    else
                    {
                        flag = true;
                    }
                }
                else
                {
                    flag = true;
                }
            }
            if (listner == null)
            {
                try
                {
                    listner = new TextWriterTraceListener(TRACE_FILE);
                    Trace.Listeners.Add(listner);
                    Trace.IndentLevel = 0;
                    Trace.AutoFlush = true;
                }
                catch (Exception)
                {
                    return;
                }
            }
            builder = new StringBuilder();
            builder.Append("[");
            builder.Append(DateTimeString);
            builder.Append("] ");
            builder.Append("[");
            builder.Append(traceName);
            builder.Append("] ");
            builder.Append(traceMessage);
            Trace.WriteLine(builder.ToString());
        }

        public static void TextTraceMonitor(string traceName, string traceMessage)
        {
            lock (lockObject)
            {
                if ((TraceLevel != 0) && WriteFlag)
                {
                    string path = Path.Combine(TracePath, DateTime.Now.ToString("yyyy-MM-dd") + ".log");
                    bool flag = false;
                    int num = 0;
                    while (!flag)
                    {
                        if (File.Exists(path))
                        {
                            FileInfo info = new FileInfo(path);
                            float num2 = ((float) info.Length) / 1000000f;
                            if (num2 > TraceSize)
                            {
                                path = Path.Combine(TracePath, DateTime.Now.ToString("yyyy-MM-dd_") + num.ToString() + ".log");
                                num++;
                            }
                            else
                            {
                                flag = true;
                            }
                        }
                        else
                        {
                            flag = true;
                        }
                    }
                    try
                    {
                        if ((TraceLogListner == null) || (LastTraceFile != path))
                        {
                            TraceLogListner = new TextWriterTraceListener(path);
                            TraceLogListner.IndentLevel = 0;
                            LastTraceFile = path;
                        }
                    }
                    catch (Exception)
                    {
                        goto Label_022C;
                    }
                    StringBuilder builder = new StringBuilder();
                    builder.Append(traceName);
                    builder.Append("||");
                    if (string.IsNullOrEmpty(ProcessID))
                    {
                        ProcessID = Process.GetCurrentProcess().Id.ToString();
                    }
                    builder.Append(ProcessID);
                    builder.Append("||");
                    if (string.IsNullOrEmpty(ProcessName))
                    {
                        ProcessName = Process.GetCurrentProcess().ProcessName;
                    }
                    builder.Append(ProcessName);
                    builder.Append("||");
                    builder.Append(DateTimeString);
                    builder.Append("||");
                    builder.Append(traceMessage);
                    builder.Append("||||");
                    TraceLogListner.WriteLine(builder.ToString());
                    TraceLogListner.Flush();
                }
            Label_022C:;
            }
        }

        public static void WriteDebugInfo(string message)
        {
            if (TraceLevel > 4)
            {
                StackFrame frame = new StackTrace().GetFrame(1);
                string str = string.Concat(new object[] { frame.GetMethod(), " at ", frame.GetMethod().ReflectedType.FullName, Seperator, message });
                string str2 = ComplexDataFlag + Seperator + "Debug" + Seperator + DateTimeString + Seperator + str;
                consoleTrace.WriteLine(str2);
                TextTraceMonitor("Debug", str.Replace(Seperator, "||"));
            }
        }

        public static void WriteError(string message)
        {
            if (TraceLevel > 0)
            {
                StackFrame frame = new StackTrace().GetFrame(1);
                string str = string.Concat(new object[] { frame.GetMethod(), " at ", frame.GetMethod().ReflectedType.FullName, Seperator, message });
                string str2 = ComplexDataFlag + Seperator + "Error" + Seperator + DateTimeString + Seperator + str;
                consoleTrace.WriteLine(str2);
                TextTraceMonitor("Error", str.Replace(Seperator, "||"));
            }
        }

        public static void WriteException(Exception ex)
        {
            if ((TraceLevel > 3) && (ex != null))
            {
                StackFrame frame = new StackTrace().GetFrame(1);
                string str = string.Concat(new object[] { frame.GetMethod(), " at ", frame.GetMethod().ReflectedType.FullName, Seperator, ex.Message, "  ", ex.StackTrace });
                string message = ComplexDataFlag + Seperator + "Warning" + Seperator + DateTimeString + Seperator + str;
                consoleTrace.WriteLine(message);
                TextTraceMonitor("Warning", str.Replace(Seperator, "||"));
            }
        }

        public static void WriteInfo(string message)
        {
            if (TraceLevel > 1)
            {
                StackFrame frame = new StackTrace().GetFrame(1);
                string str = string.Concat(new object[] { frame.GetMethod(), " at ", frame.GetMethod().ReflectedType.FullName, Seperator, message });
                string str2 = ComplexDataFlag + Seperator + "Info" + Seperator + DateTimeString + Seperator + str;
                consoleTrace.WriteLine(str2);
                TextTraceMonitor("Info", str.Replace(Seperator, "||"));
            }
        }

        [DllImport("kernel32")]
        private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);
        private static void WriteString(string file, string section, string key, string strVal)
        {
            WritePrivateProfileString(section, key, strVal, file);
        }

        public static void WriteWarning(string message)
        {
            if (TraceLevel > 2)
            {
                StackFrame frame = new StackTrace().GetFrame(1);
                string str = string.Concat(new object[] { frame.GetMethod(), " at ", frame.GetMethod().ReflectedType.FullName, Seperator, message });
                string str2 = ComplexDataFlag + Seperator + "Warning" + Seperator + DateTimeString + Seperator + str;
                consoleTrace.WriteLine(str2);
                TextTraceMonitor("Warning", str.Replace(Seperator, "||"));
            }
        }

        private static string DateTimeString
        {
            get
            {
                return DateTime.Now.ToString("HH:mm:ss.fff");
            }
        }
    }
}

